package com.naiterui.ehp.bs.pc.common.config;

import com.naiterui.ehp.bp.security.properties.SecurityProperties;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.security.HeaderConstant;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bs.pc.modules.security.utils.RsaUtil;
import feign.RequestInterceptor;
import java.net.URLEncoder;
import java.time.Duration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.crypto.password.PasswordEncoder;

@Slf4j
@Configuration
public class AppConfiguration {

  @Autowired
  private final SecurityProperties securityProperties = null;

//  @Bean
//  public InterceptorAddition interceptorAddition() {
//    return InterceptorAddition.build(new PasswordExpireInterceptor()).excludePathPatterns("/sys/menu/nav", "/sys/user/info", "/sys/user/password");
//  }

  @Bean
  public RequestInterceptor feignInterceptor() {
    return template -> {
      template.header("X-inner", "1");
      template.header(HeaderConstant.DATA_NO_WRAP, "1");
      try {
        template.header("operator", URLEncoder.encode(SecurityUtils.getCurrentUser().getUsername(), Charsets.UTF_8.name()));
      } catch (Exception ignored) {
        log.warn("增加header失败，获取当前操作人错误");
        template.header("operator", "CMS");
      }
    };
  }

  /**
   * 设置redis缓存过期时间
   */
  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(15));
    return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), redisCacheConfiguration);
  }


  @Bean
  public PasswordEncoder passwordEncoder() {
    // 密码加密方式
    return new PasswordEncoder() {
      @Override
      public String encode(CharSequence charSequence) {
        return RsaUtil.encryptData( charSequence.toString());
      }

      @Override
      public boolean matches(CharSequence charSequence, String encodePwd) {
        log.info("===jwt里加载用户信息 {}, 前端传过来的经过解密处理的数据 {}", charSequence.toString(), encodePwd);
        // encode完后的加密密码，加salt，md5，和苦衷dr_login是否一样
        // 从jwt用户信息里解出来md5加密串
        String[] pwdSalt = encodePwd.split("~");
        String salt = pwdSalt[0];
        String md5Str = pwdSalt[1];
        String sMd5Str = MD5.md5(charSequence.toString().trim() + salt);
        return sMd5Str.equals(md5Str);
      }
    };
  }
}
